<template>
  <div class="login">
    <Row type="flex" justify="center" align="middle" @keydown.enter.native="submitLogin">
      <Col style="width: 368px;">
        <Header />
        <Row>
          <Tabs v-model="tabName">
            <TabPane :label="$t('usernameLogin')" name="username" icon="md-person">
              <Form
                ref="usernameLoginForm"
                :model="form"
                :rules="rules"
                class="form"
                v-if="tabName=='username'"
              >
                <FormItem prop="organization" class="margin-bottom-3">
                  <Select v-model="form.organization" prefix="ios-home" size="large" filterable>
                    <Option v-for="item in organizationList" :key="item.id" :value="item.id">{{ item.organization_name }}
                    </Option>
                  </Select>
                </FormItem>
                <FormItem prop="mobile">
                  <Input
                    v-model="form.mobile"
                    prefix="ios-phone-portrait"
                    size="large"
                    clearable
                    placeholder="请输入登录帐号"
                    autocomplete="off"
                  />
                </FormItem>
                <FormItem prop="password">
                  <Input
                    type="password"
                    v-model="form.password"
                    prefix="ios-lock"
                    size="large"
                    password
                    placeholder="请输入密码"
                    autocomplete="off"
                  />
                </FormItem>
              </Form>
            </TabPane>
          </Tabs>
          <Row type="flex" justify="space-between" align="middle">
            <Checkbox v-model="saveLogin" size="large">{{ $t('autoLogin') }}</Checkbox>
            <router-link to="/regist?passwordOp=forgetPass" >
              <a class="forget-pass">{{ $t('forgetPass') }}</a>
            </router-link>
            <router-link to="/regist?passwordOp=activate" >
              <a class="forget-pass">{{ $t('activate') }}</a>
            </router-link>
          </Row>
          <Row>
            <Button
              class="login-btn"
              type="primary"
              size="large"
              :loading="loading"
              @click="submitLogin"
              long
            >
              <span v-if="!loading">{{ $t('login') }}</span>
              <span v-else>{{ $t('logining') }}</span>
            </Button>
          </Row>
        </Row>
        <Footer />
      </Col>
    </Row>
  </div>
</template>

<script>
import { userInfo } from "@/api/index";
import { getOrganization, getUserIsActivated, login, getUserInfo, getMenuList, getUserRole, getCompanyInfo } from "@/api/users";
import { validateMobile, validateOrganization } from "@/libs/validate";
import Cookies from "js-cookie";
import Header from "@/views/main-components/header";
import Footer from "@/views/main-components/footer";
import util from "@/libs/util.js";
import md5 from 'md5';
export default {
  components: {
    Header,
    Footer
  },
  data() {
    return {
      error: false,
      tabName: "username",
      saveLogin: true,
      loading: false,
      sending: false,
      organizationList: [],
      form: {
        organization: 0,
        password: "",
        mobile: ""
      },
      passwordOp: '',
      showActivateForm: false,
      rules: {
        password: [
          {
            required: true,
            message: "密码不能为空",
            trigger: "blur"
          }
        ],
        mobile: [
          {
            required: true,
            message: "手机号不能为空",
            trigger: "blur"
          },
          {
            validator: validateMobile,
            trigger: "blur"
          }
        ]
      }
    };
  },
  created() {
    this.getData();
    const logInfo = JSON.parse(Cookies.get("loginInfo"));
    this.form.organization = logInfo.organization_id;
    this.form.mobile = logInfo.mobile;
  },
  methods: {
    getData() {
      getOrganization().then(res => {
        if (res.code === 0) {
          this.organizationList = res.data.rows;
        }
      })
    },
    activateAccount() {
      this.passwordOp = 'activateAccount';
      this.showActivateForm = true;
    },
    forgetPassword() {
      this.passwordOp = 'forgetPassword';
      this.showActivateForm = true;
    },
    submitLogin() {
      if (this.tabName == "username") {
        this.$refs.usernameLoginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            getUserIsActivated(this.form.mobile).then(res => {
              if (res.code === 0) {
                let loginParams = {
                  organization_id: this.form.organization,
                  mobile: this.form.mobile,
                  password: md5(this.form.password)
                }
                login(loginParams).then(res => {
                  if (res.code === 0) {
                    this.setStore("accessToken", res.data.token);
                    // 获取用户信息
                    const userId = res.data.id;
                    getUserInfo({userId}).then(res => {
                      if (res.code === 0) {
                        let userInfo = res.data;
                        getCompanyInfo().then(res => {
                          if (res.code === 0) {
                            userInfo.compamy = res.data.name;
                            Cookies.set('userInfo', JSON.stringify(userInfo), {expiresIn: '8h'})
                            this.setStore('userInfo', userInfo);
                            this.$store.commit('setAvatarPath', userInfo.avatar)
                          }
                        })
                        if (this.saveLogin) {
                          let saveCookies = {
                            organization_id: userInfo.organization_id,
                            mobile: userInfo.mobile
                          }
                          // 保存7天
                          Cookies.set("loginInfo", JSON.stringify(saveCookies), {
                            expires: 7
                          });
                        } else {
                          Cookies.remove('loginInfo');
                        }
                        
                        // 获取菜单
                        getMenuList({userId}).then(res => {
                          if (res.code === 0) {
                            const menuData = res.data;
                            this.setStore('menuData', menuData);
                          }
                          // 获取角色
                          getUserRole({userId}).then(res => {
                            if (res.code === 0) {
                              let roles = [];
                              res.data.forEach(e => {
                                roles.push(e.name);
                              });
                              this.setStore('roles', roles);
                            }
                          })
                          util.initRouter(this);
                          this.$router.push({
                            name: "home_index"
                          });
                        })
                      }
                    })
                        
                  } else {
                    this.$Message.error(res.message); //登录失败
                    this.loading = false;
                  }
                })
              } else {
                this.$Message.error(res.message); //未激活
                this.loading = false;
              }
            })
          }
        });
      }
    },
  },
  mounted() {}
};
</script>

<style lang="less">
@import "./login.less";
</style>
